// 天气预报store - 选项式API
import { defineStore } from 'pinia'
import weatherApi from '../api/weather'

export const useWeatherStore = defineStore('weather', {
  state: () => ({
    weatherData: null,
    cityInfo: null,
    forecast: [],
    loading: false,
    error: null,
    lastUpdated: null
  }),
  
  getters: {
    // 获取当前天气概况
    weatherSummary(state) {
      if (!state.weatherData || !state.cityInfo) return null
      
      const { wendu, shidu, quality, ganmao } = state.weatherData
      const { city } = state.cityInfo
      
      return {
        city,
        temperature: wendu,
        humidity: shidu,
        airQuality: quality,
        healthTip: ganmao
      }
    },
    
    // 获取天气预报数据
    forecastData(state) {
      return state.forecast
    },
    
    // 获取更新时间
    updateTime(state) {
      return state.lastUpdated
    },
    
    // 判断是否有数据
    hasData(state) {
      return !!state.weatherData
    }
  },
  
  actions: {
    // 获取天气数据
    async fetchWeatherData(cityCode) {
      this.loading = true
      this.error = null
      
      try {
        const response = await weatherApi.getWeatherByCity(cityCode)
        
        // 保存数据到state
        this.weatherData = response.data
        this.cityInfo = response.cityInfo
        this.forecast = response.data.forecast
        this.lastUpdated = new Date().toLocaleString()
        
        return response
      } catch (error) {
        this.error = error.message || '获取天气数据失败'
        console.error('获取天气数据失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取天气概况
    async getWeatherSummary(cityCode) {
      if (!this.weatherData || this.cityInfo?.citykey !== cityCode) {
        await this.fetchWeatherData(cityCode)
      }
      
      const { city } = this.cityInfo
      const { wendu, shidu, quality, ganmao } = this.weatherData
      
      return `当前${city}的天气：温度${wendu}℃，湿度${shidu}，空气质量${quality}。${ganmao}`
    },
    
    // 重置store状态
    resetState() {
      this.weatherData = null
      this.cityInfo = null
      this.forecast = []
      this.loading = false
      this.error = null
      this.lastUpdated = null
    }
  }
})
